package com.twu.biblioteca.services;

import com.twu.biblioteca.Constants.Books;
import com.twu.biblioteca.elements.Book;
import com.twu.biblioteca.helper.ServiceHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookLogicService {
    private Books books;
    private List<Book> allBooksInLibrary;

    public BookLogicService(Books books) {
        this.books = books;
        allBooksInLibrary = books.getAllBooks();
    }

    public Book getBookByBookName(String chosenBookName) {
        for (Book book : allBooksInLibrary) {
            if (book.getBookName().equals(chosenBookName)) {
                return book;
            }
        }
        return null;
    }

    public List<Book> getAllAvailableBooksInTheLibrary() {
        ArrayList<Book> availableBooks = new ArrayList<Book>();

        for (Book book : allBooksInLibrary) {
            if (book.isAvailable) {
                availableBooks.add(book);
            }
        }
        return availableBooks;
    }

    public boolean bookIsAvailable(String chosenBookName) {
        return getAllAvailableBooksNameInLibrary().contains(chosenBookName);
    }

    public Map<String, String> getChosenBookNameAndStatus() throws IOException {
        String readerName = ServiceHelper.getInputValue();
        String chosenBookName = String.valueOf(readerName);
        boolean isAvailable = bookIsAvailable(chosenBookName);

        HashMap<String, String> bookAvailableMap = new HashMap<String, String>();
        bookAvailableMap.put("bookName", chosenBookName);
        bookAvailableMap.put("isAvailable", String.valueOf(isAvailable));

        return bookAvailableMap;
    }

    private List<String> getAllAvailableBooksNameInLibrary() {
        List<Book> availableBooks = getAllAvailableBooksInTheLibrary();

        ArrayList<String> bookNameList = new ArrayList<String>();
        for (Book book : availableBooks) {
            bookNameList.add(book.getBookName());
        }
        return bookNameList;
    }

    public void checkoutBookSuccessfully(Book book, String owner) {
        book.setAvailable(false);
        book.setOwner(owner);
    }

    public boolean returnBook(String bookName) {
        Book book = getBookByBookName(bookName);
        boolean bookIsNotFromLibrary = book == null;
        if (bookIsNotFromLibrary) {
            return false;
        }
        book.setAvailable(true);
        book.setOwner(null);
        return true;
    }
}
